﻿
using System;
using System.Security.Claims;

namespace RayD.Core 
{
    /// <summary>
    /// 自定义Session（基于AuthenticationCookie 与 系统默认Cache）
    /// 使用的前提是AuthenticationCookie存在，否则报错
    /// </summary>
    public class CustomSession
    {
        #region 私有成员
        /// <summary>
        /// 缓存模块名称
        /// </summary>
        private static string CacheModuleName { get; } = "Session";
        /// <summary>
        /// 获取登录基础Cookie信息中存储的SessionId
        /// </summary>
        private static string _sessionId { get => AuthenticationHelper.Get(ClaimTypes.Sid); }
        /// <summary>
        /// 构建缓存键
        /// </summary>
        /// <param name="sessionKey">后缀</param>
        /// <returns></returns>
        private static string BuildCacheKey(string sessionKey)
        {
            return $"{AppSettings.ProjectName.EName}_{CacheModuleName}_{_sessionId}_{sessionKey}";
        }

        #endregion

        #region 外部成员

        /// <summary>
        /// 存放Session标志的Cookie名
        /// </summary>
        //public static string SessionCookieName { get; } = $".AspNetCore.{CookieKey.CookieAuthenticationScheme}";

        /// <summary>
        /// 当前Session
        /// </summary>
        public static _Session Session { get; } = new _Session();

        /// <summary>
        /// 自定义_Session类
        /// </summary>
        public class _Session
        {
            public object this[string index]
            {
                get
                {
                    string cacheKey = BuildCacheKey(index);
                    return CacheHelper.Cache.GetCache(cacheKey);
                }
                set
                {
                    string cacheKey = BuildCacheKey(index);
                    if (value.IsEmpty())
                        CacheHelper.Cache.RemoveCache(cacheKey);
                    else
                        CacheHelper.Cache.SetCache(cacheKey, value,TimeSpan.FromMinutes(Define.EXPIRETIME),ExpireType.Relative);
                }
            }
        }

        /// <summary>
        /// 清除Session的Cookie
        /// </summary>
        public static void RemoveSessionCookie()
        {
            AuthenticationHelper.Clear();
        }

        #endregion
    }
}
